<template>
  <el-card style="width: 100%">
    <el-row :gutter="20" class="header">
      <el-col :span="7">
        <!-- 搜索框 -->
        <el-input
          :placeholder="$t('table.placeholder')"
          clearable
          v-model="queryForm.search"
        ></el-input>
      </el-col>
      <!-- 搜索 -->
      <el-button type="primary" :icon="Search" @click="initGetList">
        {{ $t("table.search") }}
      </el-button>
      <!-- 添加菜单 -->
      <el-button type="primary" @click="handlerDialogValue()">
        {{ $t("menu.addMenu") }}
      </el-button>
    </el-row>

    <!-- 菜单列表 -->
    <el-table
      :data="tableData"
      border
      class="listTable"
      row-key="menuId"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      :expand-row-keys="expandedKeys"
    >
      <!-- 动态生成表格列 -->
      <el-table-column
        v-for="option in tableOptions"
        :key="option.prop"
        :prop="option.prop"
        :label="option.label"
        :width="option.width"
        :formatter="option.formatter"
      >
        <!-- 图标列的特殊处理 -->
        <template #default="{ row }" v-if="option.prop === 'menuIcon'">
          <el-icon v-if="row.menuIcon">
            <component :is="row.menuIcon" />
          </el-icon>
        </template>
      </el-table-column>

      <!-- 操作列 -->
      <el-table-column :label="$t('common.actions')" width="200" fixed="right">
        <template #default="{ row }">
          <el-button-group>
            <el-button size="small" @click="handlerDialogValue(row)">
              <el-icon><View /></el-icon>
            </el-button>
            <el-button
              size="small"
              type="primary"
              @click="handlerDialogValue(row)"
            >
              <el-icon><Edit /></el-icon>
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="deleteMenuHandler(row)"
            >
              <el-icon><Delete /></el-icon>
            </el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>
  </el-card>

  <!-- 弹窗组件 -->
  <Dialog
    v-model:modelValue="dialogVisible"
    :dialogTitle="dialogTitle"
    v-if="dialogVisible"
    @initGetList="initGetList"
    :dialogTableValue="dialogTableValue"
  />
</template>

<script setup>
import { ref } from "vue";
import { Delete, Edit, Search, View } from "@element-plus/icons-vue";
import { getMenus, deleteMenu } from "@/api/menu";
import { ElMessage, ElMessageBox } from "element-plus";
import { options as tableOptions } from "./options";
import { useI18n } from "vue-i18n";
import Dialog from "./components/dialog.vue";
import { isNull } from "@/utils/filters";
import { formatTreeData } from "@/utils/public";

const i18n = useI18n();

// 查询表单
const queryForm = ref({
  search: "",
  page: 1,
  pageSize: 10,
});

// 表格数据
const tableData = ref([]);
const total = ref(0);

// 在 script setup 中添加 expandedKeys ref
const expandedKeys = ref([]);

// 获取菜单列表
const initGetList = async () => {
  try {
    const res = await getMenus(queryForm.value);
    total.value = res.data.total;
    // 将扁平数据转换为树形结构
    tableData.value = formatTreeData(res.data.data, "menuId", "menuParentId");
    // 设置第一层节点的展开
    expandedKeys.value = tableData.value.map((item) => item.menuId);
    console.log("树形数据:", tableData.value);
  } catch (error) {
    console.error("获取菜单列表失败:", error);
  }
};

// 初始化加载
initGetList();

// 分页处理
const handleSizeChange = (pageSize) => {
  queryForm.value.page = 1;
  queryForm.value.pageSize = pageSize;
  initGetList();
};

const handleCurrentChange = (page) => {
  queryForm.value.page = page;
  initGetList();
};

// 弹窗控制
const dialogVisible = ref(false);
const dialogTitle = ref("");
const dialogTableValue = ref({});

// 处理弹窗显示
const handlerDialogValue = (row) => {
  if (isNull(row)) {
    dialogTitle.value = i18n.t("menu.addMenu");
    dialogTableValue.value = {};
  } else {
    dialogTitle.value = i18n.t("menu.editMenu");
    dialogTableValue.value = JSON.parse(JSON.stringify(row));
  }
  dialogVisible.value = true;
};

// 删除菜单
const deleteMenuHandler = (row) => {
  ElMessageBox.confirm(
    i18n.t("dialog.deleteConfirm"),
    i18n.t("dialog.warning"),
    {
      confirmButtonText: i18n.t("common.confirm"),
      cancelButtonText: i18n.t("common.cancel"),
      type: "warning",
    }
  )
    .then(async () => {
      await deleteMenu(row.menuId);
      ElMessage({
        type: "success",
        message: i18n.t("dialog.deleteSuccess"),
      });
      initGetList();
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: i18n.t("dialog.deleteCanceled"),
      });
    });
};
</script>

<style src="@/css/list.css"></style>
